<template>
	<div>
		<div class="container">
			<h2 style="text-align: center;">机械申请计划</h2>
			<div class="toolbar">
				<a-form ref="searchRef" layout="inline" :model="searchState" @finish="current=1;loading=true;initData()">
					<a-form-item label="城市公司/专业公司">
						<a-select v-model:value="searchState.company_id" :show-search="true" placeholder="请选择城市公司/专业公司" :options="companyOptions" option-filter-prop="label" allow-clear></a-select>
					</a-form-item>
					<a-form-item label="选择项目">
						<a-select v-model:value="searchState.project_id" style="width:200px" :show-search="true" placeholder="请选择项目" :options="innerProjectOptions" option-filter-prop="label" allow-clear></a-select>
					</a-form-item>

					<a-form-item label="编号">
						<a-input v-model:value="searchState.code" placeholder="请输入" allow-clear></a-input>
					</a-form-item>

					<a-form-item>
						<a-space>
							<a-button type="primary" html-type="submit">
								<search-outlined />搜索
							</a-button>
							<a-button v-permission="40" type="primary" danger @click="addMachineapply()">
								<plus-outlined />创建新计划
							</a-button>
						</a-space>
					</a-form-item>
				</a-form>
			</div>

			<div class="mt-2">
				<!--
				v-if="!loading"使得:default-expand-all-rows="true"生效
				-->
				<a-table v-if="!loading" :columns="columns" :scroll="tableScroll" row-key="id" children-column-name="children" :default-expand-all-rows="false" :data-source="maSource" :pagination="pagination" :loading="loading" :row-class-name="(record, index) => (record.is_invalid === 1 ? 'table-striped' : null)" @change="initData">
					<template #bodyCell="{ column, record }">
						<template v-if="column.key === 'operation'">
							<a-space>
								<a-button v-permission="42" type="link" @click="showMachineapply(record)">
									<diff-outlined />查看
								</a-button>
								<template v-if="![0,1,2].includes(record.workflow_status)">
									<a-button v-permission="41" type="link" @click="editMachineapply(record)">
										<edit-outlined />修改
									</a-button>
									<a-button v-permission="118" type="link" style="color:#ff7875" @click="deleteMachineapply(record.id)">
										<delete-outlined />删除
									</a-button>
								</template>
								<a-button v-if="record.workflow_status === 2 && record.purchase_quantity === 0 && !record.is_invalid" v-permission="41" type="link" style="color:#ff7875" @click="nullifyPurchase(record.id)">
									<PoweroffOutlined />作废
								</a-button>
							</a-space>
						</template>
						<template v-else-if="column.dataIndex === 'workflow_status'">
							<div>
								<a-workflow type="status" module="machineapply" :status="record.workflow_status" />
							</div>
						</template>
					</template>
				</a-table>
			</div>
		</div>
		<a-modal v-model:visible="visible" :width="1200" :title="`${formState.id ? '修改' : '添加'}机械预约单`" @ok="saveJx">
			<a-form ref="formRef" :model="formState" v-bind="{labelCol: { style: { width: '180px' } }}">
				<a-form-item label="机械配置计划" name="plan_id" :rules="{required:true, message:'请选择机械配置计划'}">
					<a-select v-model:value="formState.plan_id" :disabled="disabled" :show-search="true" placeholder="请选择机械配置计划" :options="planOptions" option-filter-prop="label" @change="choosePlan"></a-select>
				</a-form-item>
				<a-form-item label="项目名称" name="project_id" :rules="{required:true, message:'请选择项目'}">
					<a-select v-model:value="formState.project_id" disabled="disabled" :show-search="true" placeholder="请选择项目" :options="projectOptions" option-filter-prop="label"></a-select>
				</a-form-item>
				<a-form-item label="工作内容" name="usefor" :rules="{required:true, message:'请输入工作内容'}">
					<a-input v-model:value="formState.usefor" :disabled="disabled" />
				</a-form-item>
				<a-form-item label="使用时间" name="apply_time" :rules="{required:true, message:'请输入使用时间'}">
					<a-date-picker v-model:value="formState.apply_time" :disabled="disabled" :picker="date_type" value-format="YYYY-MM-DD" />
				</a-form-item>
				<a-form-item label="使用次（天）数" name="use_times" :rules="{required:true, message:'请输入使用次（天）数'}">
					<a-input v-model:value="formState.use_times" :disabled="disabled" />
				</a-form-item>
				<a-form-item label="计量单位" :name="time_unit" :rules="{required:true, message:'请选择时长计量单位'}">
					<a-select v-model:value="formState.time_unit" :disabled="disabled" :show-search="true" placeholder="请选择时长计量单位" :options="timeunitOptions" :field-names="{value:'name'}"></a-select>
				</a-form-item>
				<a-form-item label="备注" name="memo">
					<a-input v-model:value="formState.memo" :disabled="disabled" />
				</a-form-item>
			</a-form>
		</a-modal>
	</div>
</template>

<script setup>
import { reactive, ref, computed, getCurrentInstance } from "vue";

import dayjs from "dayjs";

import { SearchOutlined, PlusOutlined, EditOutlined, DeleteOutlined, DiffOutlined, PoweroffOutlined } from "@ant-design/icons-vue";

import { post } from "../utils";

import { usePagination } from "vue-request";
import router from "../router";
import { AWorkflow } from "@/components/index.js";
import { useRoute } from "vue-router";

const searchRef = ref();
const searchState = reactive({});
const visible = ref(false);
const formState = ref({});
const disabled = ref(false);
const planOptions = ref([]);
const route = useRoute();
const query = route.query;
const choosePlan = value => {
	const plan_id = value;
	formState.value.plan_id = plan_id;
	post("plan/info", { id: value }).then(data => {
		formState.value.project_id = data.project_id;
	});
};
const columns = [
	{
		title: "序号",
		dataIndex: "id",
		key: "id",
		width: 80,
		align: "left",
		fixed: "left"
	},
	{
		title: "编号",
		dataIndex: "code",
		sorter: false,
		width: 150,
		ellipsis: true,
		fixed: "left"
	},
	{
		title: "项目名称",
		dataIndex: "project",
		sorter: false,
		ellipsis: true,
		customRender: ({ text, record, index, column }) => {
			return text?.name;
		}
	},
	{
		title: "联系人",
		dataIndex: "receiver",
		sorter: false,
		ellipsis: true
	},
	{
		title: "联系电话",
		dataIndex: "receiver_tel",
		sorter: false,
		ellipsis: true
	},
	{
		title: "申请人",
		dataIndex: "applier",
		ellipsis: true,
		customRender: ({ text, record, index, column }) => {
			return text.fullname || text.username;
		}
	},
	{
		title: "申请时间",
		dataIndex: "create_time",
		width: 180,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return dayjs(text).format("YYYY-MM-DD HH:mm:ss");
		}
	},
	{
		title: "采购状态",
		dataIndex: "purchase_Surplus_quantity",
		sorter: false,
		width: 100,
		ellipsis: true,
		customRender: ({ text, record, index, column }) => {
			return text > 0 ? "采购未完成" : "采购完成";
		}
	},
	{
		title: "状态",
		dataIndex: "workflow_status",
		sorter: false,
		width: 70,
		ellipsis: true,
	},
	{
		title: "操作",
		key: "operation",
		sorter: false,
		fixed: "right",
		width: 170,
		align: "center"
	}
];
const tableScroll = computed(() => ({ x: document.documentElement.clientWidth - 650 }));
const projectOptions = ref([]);
const companyOptions = ref([]);
const getProjects = async () => {
	const projectResult = await post("department/projects?type=3", { page_size: 1000 });
	projectOptions.value = projectResult.data.map(d => {
		return {
			value: d.id,
			label: d.name,
			parseIds: d.parent_ids.split(',').map(item => parseInt(item)),
		};
	});
};
if (!projectOptions.value.length) {
	getProjects();
}
post("department/projects?type=2", {
	parent_ids: JSON.stringify([78, 24]),
}).then(({ data }) => {
	companyOptions.value = data.map(d => {
		return {
			value: d.id,
			label: d.name
		};
	});
});
const innerProjectOptions = computed(() => {
	let options = [];
	if (!projectOptions.value.length) return options;
	if (searchState.company_id) {
		options = projectOptions.value.filter((item) => {
			return item.parseIds.includes(searchState.company_id);
		})
	} else {
		options = projectOptions.value;
	}
	if (!options.filter(item => item.value === searchState.project_id).length) {
		searchState.project_id = null;
	}
	return options;
})
const { data, loading, run, current, pageSize, total } = usePagination(async params => {
	const search = { };
	if (searchState.company_id) {
		if (!projectOptions.value.length) await getProjects();
		search.project_ids = projectOptions.value.filter((item) => {
			return item.parseIds.includes(searchState.company_id);
		}).map(item => item.value).join(',');
		if (!search.project_ids) {
			return [];
		}
	}
	return post("machineapply", { ...params, ...searchState, ...search });
}, {
	defaultParams: [
		{
			page_size: 20
		}
	],
	pagination: {
		currentKey: "page",
		pageSizeKey: "page_size",
		totalKey: "total"
	}
});

const timeunitOptions = ref([]);
post("dictionary", { root_code: "MATERIAL_TIMEUNIT" }).then(data => {
	timeunitOptions.value = data;
});
post("plan", { type: 3, page_size: 1000 }).then(({ data }) => {
	planOptions.value = data.map(d => {
		return {
			value: d.id,
			label: d.name
		};
	});
});
const maSource = computed(() =>
	(data.value?.data || []).map(d => {
		if (d.children?.length === 0) delete d.children;
		return d;
	})
);
const addMachineapply = () => {
	router.push("/machineapply/create");
	// disabled.value = false;
	// formRef.value?.clearValidate();
	// visible.value = true;
	// formState.value = {};
};
const editMachineapply = record => {
	router.push(`/machineapply/edit/${record.id}`);
	// disabled.value = false;
	// visible.value = true;
	// formState.value = { ...record };
};
const showMachineapply = record => {
	router.push(`/machineapply/info/${record.id}`);
	// disabled.value = true;
	// visible.value = true;
	// formState.value = { ...record };
};

const pagination = computed(() => ({
	total: total.value,
	current: current.value,
	pageSize: pageSize.value
}));

const initData = (pag, filters, sorter) => {
	pag = Object.assign(
		{
			current: current.value,
			pageSize: pageSize.value
		},
		pag || {}
	);
	filters = { ...filters, ...searchState };
	const query = {};
	if (pag?.pageSize) {
		query['page_size'] = pag?.pageSize;
	}
	if (pag?.current) {
		query['page'] = pag?.current;
	}
	router.replace({ query: {
		...query,
		...filters
	}})
	run({
		page_size: pag?.pageSize,
		page: pag?.current,
		sort_field: sorter?.field,
		sort_order: sorter?.order,
		...filters
	});
};
if (query) {
	if (query.company_id) searchState.company_id = parseInt(query.company_id);
	if (query.project_id) searchState.project_id = parseInt(query.project_id);
	if (query.code) searchState.code = query.code;
	// router.replace({ query: {}})
	const pag = {};
	if (query.page) {
		pag['current'] = parseInt(query.page);
	}
	if (query.pageSize) {
		pag['pageSize'] = parseInt(query.page_size);
	}
	initData(pag);
}

const formRef = ref();
const { proxy } = getCurrentInstance();
const saveJx = () => {
	formRef.value
		.validate()
		.then(() => {
			proxy.$message.destroy();

			const params = { ...formState.value };
			post("machineapply/save", params)
				.then(() => {
					proxy.$message.success("提交成功", 1);
					visible.value = false;

					initData();
				})
				.catch(err => {
					proxy.$message.error(err);
				});
		})
		.catch(err => {});
};
const deleteMachineapply = id => {
	proxy.$confirm({
		title: "确认提示",
		content: `确定要删除${typeof id === "number" ? "当前" : "选中"}的记录吗？`,
		okText: "确认",
		cancelText: "取消",
		onOk() {
			post("machineapply/delete", { id }).then(() => {
				proxy.$message.success("删除成功");
				initData();
			});
		}
	});
};
const nullifyPurchase = id => {
	proxy.$confirm({
		title: "确认提示",
		content: `确定要作废${typeof id === "number" ? "当前" : "选中"}的记录吗？`,
		okText: "确认",
		cancelText: "取消",
		onOk() {
			post("machineapply/invalid", { id }).then(() => {
				proxy.$message.success("记录作废成功");
				initData();
			}).catch((err) => {
				proxy.$message.warning(err);
			});
		}
	});
};
</script>
<style scoped lang="scss">
.container {
	background: #fff;
	padding: 12px;
}
:deep(.ant-input[disabled]) {
	color: rgba(0, 0, 0, 0.65);
	background: #fff;
	border: 1px solid #d9d9d9;
}
:deep(.ant-input-disabled) {
	color: rgba(0, 0, 0, 0.65);
	background: #fff;
	border: 1px solid #d9d9d9;
}

:deep(.ant-select-disabled.ant-select:not(.ant-select-customize-input) .ant-select-selector) {
	color: rgba(0, 0, 0, 0.65);
	background: #fff;
	border: 1px solid #d9d9d9;
}
:deep(.ant-picker-input > input[disabled]) {
	color: rgba(0, 0, 0, 0.65);
	background: #fff;
	border: 1px solid #d9d9d9;
}
//.ant-picker.ant-picker-disabled
:deep(.ant-picker.ant-picker-disabled) {
	color: rgba(0, 0, 0, 0.65);
	background: #fff;
	border: 1px solid #d9d9d9;
}
</style>
<style lang="scss">
.table-striped{
	td{
		background-color: #d8d7d7;
	}
}
</style>
